const inquirer = require('inquirer')
const fs = require('fs-extra')
const shell = require('shelljs')
const moment = require('moment')
const print = require('../../lib/print')
const utils = require('../../lib/utils')

const _templateName = 'TemplateFramework'
// 目标文件夹路径
var _targetPath = null
var _targetName = null
var _targetAuthor = null
var _targetOrganization = null


module.exports = async function() {
    try {
        // 1.
        let params = await inputParams()
        _targetPath = `${params.projectPath}/${params.projectName}`
        _targetName = params.projectName
        _targetAuthor = params.projectAuthor
        _targetOrganization = params.projectOrganization
        // 2.
        checkoutTargetPath()
        // 3.
        cpTemplateToTarget()
        // 4. 
        modifyTemplate(_targetPath)

        print.successLog(`已创建 ${_targetPath}`)
        shell.exec(`open ${_targetPath}`)
    } catch (error) {
        print.errorLog(error)
    }
}

/*
 * 键盘输入部分，获取自定义信息
 */
function inputParams() {
    let promptList = [
        {
            type: "input",
            message: "请输入工程存放的目录：",
            name: "projectPath",
            default: process.cwd()
        },
        {
            type: "input",
            message: "请输入工程名：",
            name: "projectName"
        },
        {
            type: "input",
            message: "请输入作者：",
            name: "projectAuthor"
        },
        {
            type: "input",
            message: "请输入组织：",
            name: "projectOrganization"
        }
    ];
    return new Promise((resolve, reject) => {
        inquirer.prompt(promptList)
            .then(answer => {
                resolve(answer)
            })
    })
}

/*
 * 校验目标路径下是否存在同名文件夹
 */
function checkoutTargetPath() {
    if (fs.existsSync(_targetPath)) {
        throw `${_targetPath} 目录已存在`
    }
    fs.mkdirSync(_targetPath)
}

/*
 * 解压、复制模板文件夹下的内容到目标路径下
 */
function cpTemplateToTarget() {
    let resourcePath = `${utils.getResourcesPath()}/create_framework_project`
    let templatePath = `${resourcePath}/${_templateName}`
    let templateZip = `${templatePath}.zip`
    // 在资源目录下解压，不需要解压 __MACOSX 文件
    shell.exec(`unzip -o ${templateZip} -x __MACOSX/* -d ${resourcePath}`, {silent: true})
    print.successLog('已解压模板')
    // 遍历复制
    shell.ls(templatePath).forEach(element => {
        shell.cp('-r', `${templatePath}/${element}`, _targetPath)
    })
    print.successLog('已拷贝模板内容')
    // 删除解压的模板
    shell.rm('-r', templatePath)
    print.successLog('已删除解压的模板')
}

/*
 * 重点：遍历模板文件，执行重命名、替换操作
 */
function modifyTemplate(folder_path) {
    shell.ls(folder_path).forEach(element => {
        // 1. 重命名
        element = renameFile(element, folder_path)
        let element_path = `${folder_path}/${element}`

        let stat = fs.statSync(element_path)
        if (stat.isFile()) { // 文件
            // 2. 替换文件内容
            replaceFileContent(element_path)
        }else { // 文件夹
            // 递归查询
            modifyTemplate(element_path)
        }
    })
}

/*
 * 重命名文件、文件夹
 */
function renameFile(fileName, folderPath) {
    if (fileName.includes(_templateName)) {
        let newFileName = fileName.replace(_templateName, _targetName)
        shell.mv(`${folderPath}/${fileName}`, `${folderPath}/${newFileName}`)
        print.successLog(`已重命名 ${folderPath}/${fileName} ==> ${folderPath}/${newFileName}`)
        return newFileName
    }
    return fileName
}

/*
 * 替换文件内容
 * - TemplateFramework 替换为 自定义的项目名
 * - templateAuthor 替换为 自定义的作者
 * - templateOrganization 替换为 自定义的组织
 * - 2020/12/21 替换为 当前时间
 */
function replaceFileContent(filePath) {
    // 注意：替换时间时，/ 需要写成 \\/，如 2020\\/12\\/21
    let cur_ymd = `${moment().format('YYYY')}\\/${moment().format('MM')}\\/${moment().format('DD')}`
    let modify_cmd = `sed -i "" ` + 
                     `-e 's/TemplateFramework/${_targetName}/g' ` +
                     `-e 's/templateAuthor/${_targetAuthor}/g' ` + 
                     `-e 's/templateOrganization/${_targetOrganization}/g' ` +
                     `-e "s/2020\\/12\\/21/${cur_ymd}/g" ` +
                     `${filePath}`
    shell.exec(modify_cmd)
    print.successLog(`已替换 ${filePath}`)
}